<template>
    <div class="app-container">
        <div class="controls-container">
            <!-- 下拉选择学期 -->
            <el-select class="control-item semester-select" v-model="semesterId" placeholder="请选择学期"
                @change="changeSemester">
                <el-option v-for="(item, index) in semesterData" :key="index" :value="item.id"
                    :label="item.semesterName"></el-option>
            </el-select>
            <!-- 下拉选择教师 -->
            <el-select class="control-item class-select" @change="handleSelectChange" @clear="clearListener" clearable
                v-model="teacherNo" placeholder="请选择教师">
                <el-option v-for="(item, index) in teacherData" :key="index" :value="item.teacherNo"
                    :label="item.teacherName"></el-option>
            </el-select>
            <el-button class="control-item" type="primary" @click="exportExcel">导出课表</el-button>
        </div>
        <br />
        <el-table :data="classTableData.lessons" border style="width: 100%" id="my-table">
            <!-- 时间列 -->
            <el-table-column prop="name" label="时间" width="180">
                <template #default="scope">
                    <p>{{ "第" + digital2Chinese(scope.$index + 1) + "节" }}</p>
                    <p class="period">{{ scope.row }}</p>
                </template>
            </el-table-column>

            <!-- 周次和课程信息列 -->
            <el-table-column v-for="(weekNum, weekIndex) in classTableData.courses" :key="weekIndex"
                :label="'周' + digital2Chinese(weekIndex + 1, 'week')" width="180">
                <template #default="scope">
                    <div class="course-info" v-html="classTableData.courses[weekIndex][scope.$index]"></div>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx'; // 保持 XLSX 的导入方式
import { ElMessage } from 'element-plus';
import axios from 'axios';

const teacherData = ref([]);
const semesterData = ref([]);
const teacherNo = ref('');
const semesterId = ref('');
const listLoading = ref(true);

const classTableData = ref({
    lessons: [
        "08.20-09.55",
        "10.15-11.50",
        "14.20-15.55",
        "16.15-17.50",
        "18.30-20.05",
    ],
    courses: [[], [], [], [], [], [], []],
    timetableId: [[], [], [], [], [], [], []], // 确保 timetableId 和 timeslot 也被初始化
    timeslot: [[], [], [], [], [], [], []],
});

const changeSemester = () => {
    clearListener();
    // 如果需要根据学期重新获取教师列表或课表，在此调用相应函数
    // getList(); // 示例：如果 getList 需要根据 semesterId 筛选
    queryClass(); // 当学期改变时，如果教师已选，则查询课表
};


const initClassTableData = () => {
    classTableData.value = {
        lessons: [
            "08.20-09.55",
            "10.15-11.50",
            "14.20-15.55",
            "16.15-17.50",
            "18.30-20.05",
        ],
        courses: Array(7).fill(null).map(() => Array(5).fill('')), // 初始化为7天5节课的空字符串
        timetableId: Array(7).fill(null).map(() => Array(5).fill(-1)),
        timeslot: Array(7).fill(null).map(() => Array(5).fill(-1)),
    };
    return true;
};

const setToTable = (ret) => {
    if (!initClassTableData()) {
        return;
    }

    let flag = false; // flag为true表示 全空
    if (teacherNo.value == "" || semesterId.value == null) {
        flag = true;
    }

    if (flag || !ret || ret.length === 0) {
        if (!flag) ElMessage({ message: "暂无课表数据", type: "info" });
        return;
    }

    ret.forEach(item => {
        if (item && typeof item.timeslot !== 'undefined') {
            const dayOfWeek = Math.floor(item.timeslot / 5); // 0-6 for Mon-Sun
            const lessonOfDay = item.timeslot % 5; // 0-4 for lessons 1-5

            if (dayOfWeek < 7 && lessonOfDay < 5) {
                let section =
                    "(" +
                    (lessonOfDay * 2 + 1) +
                    "-" +
                    (lessonOfDay * 2 + 2) +
                    "节)";
                let biweekly =
                    item.biweekly == 1 ? "(单)" : item.biweekly == 2 ? "(双)" : "";
                let time =
                    section + item.startWeek + "-" + item.endWeek + "周" + biweekly;
                let className = item.className || '';
                let teacherName = item.teacherName || '';
                let course = (item.courseNo || '') + "-" + (item.courseName || '');
                let roomName = item.roomName || ''; // 假设有教室名称字段
                let size = item.size || '';

                let msg =
                    `${time}<br/>${className}<br/>${course}<br/>${roomName}`;
                // 如果需要显示教师和选课人数，可以取消注释或调整
                // msg += `<br/>${teacherName}<br/>选课人数：${size}`;

                if (classTableData.value.courses[dayOfWeek][lessonOfDay] === '') { // FIX: lessOfDay -> lessonOfDay
                    classTableData.value.courses[dayOfWeek][lessonOfDay] = msg; // FIX: lessOfDay -> lessonOfDay
                    classTableData.value.timetableId[dayOfWeek][lessonOfDay] = item.id; // FIX: lessOfDay -> lessonOfDay
                } else {
                    classTableData.value.courses[dayOfWeek][lessonOfDay] += "<br/>---<br/>" + msg; // FIX: lessOfDay -> lessonOfDay
                    classTableData.value.timetableId[dayOfWeek][lessonOfDay] += "@@@" + item.id; // FIX: lessOfDay -> lessonOfDay
                }
                classTableData.value.timeslot[dayOfWeek][lessonOfDay] = item.timeslot; // FIX: lessOfDay -> lessonOfDay
            }
        }
    });

    if (ret.length === 0 && !flag) {
        ElMessage({ message: "暂无课表", type: "success" });
    }
};

// 根据学期和教师查询课表
const queryClass = async () => {
    if (!semesterId.value || !teacherNo.value) {
        // ElMessage.info("请先选择学期和教师");
        initClassTableData(); // 清空课表
        return;
    }
    listLoading.value = true;
    try {
        const response = await axios.get(
            `/api/timetable/teacher/${semesterId.value}/${teacherNo.value}`,{
              headers: {
                "token": localStorage.getItem("token"),
              },
            }
        );
        const ret = response.data.data;
        setToTable(ret);
    } catch (error) {
        console.error("查询课表失败:", error);
        ElMessage.error("查询课表失败");
        initClassTableData(); // 查询失败也清空课表
    } finally {
        listLoading.value = false;
    }
};

//获得教师列表
const getTeacherNo = async () => {
    listLoading.value = true;
    try {
        const response = await axios.get("/api/teacher/getList",{
          headers: {
            "token": localStorage.getItem("token"),
          },
        });
        teacherData.value = response.data.data || [];
    } catch (error) {
        console.error("查询教师列表失败:", error);
        ElMessage.error("查询教师列表失败");
    } finally {
        listLoading.value = false;
    }
};

//获得学期列表
const getSemester = async () => {
    listLoading.value = true;
    try {
        // 注意：URL中的 localhost:8081 可能是开发环境地址，部署时需要修改
        const response = await axios.get("/api/semester/getList",{
          headers: {
            "token": localStorage.getItem("token"),
          },
        });
        semesterData.value = response.data.data || [];
        semesterId.value = semesterData.value[0].id;
        // 如果学期和教师都已选，则查询课表
        if (semesterId.value && teacherNo.value) {
            queryClass();
        }

    } catch (error) {
        console.error("查询学期列表失败:", error);
        ElMessage.error("查询学期列表失败");
    } finally {
        listLoading.value = false;
    }
};

const exportExcel = () => {
    try {
        const table = document.getElementById("my-table");
        if (!table) {
            ElMessage.error("找不到课表元素");
            return;
        }
        const ws = XLSX.utils.table_to_sheet(table);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

        const defaultColWidth = 20;
        const range = XLSX.utils.decode_range(ws["!ref"]);
        if (!ws["!cols"]) ws["!cols"] = [];
        for (let C = range.s.c; C <= range.e.c; ++C) {
            ws["!cols"][C] = { width: defaultColWidth };
        }

        const defaultRowHeight = 100;
        if (!ws["!rows"]) ws["!rows"] = [];
        ws["!rows"][0] = { hpx: 20 };

        for (
            let R = 1;
            R <= Math.min(6, range.e.r); // 确保不超过实际行数
            ++R
        ) {
            ws["!rows"][R] = { hpx: defaultRowHeight };
        }

        const wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
        const blob = new Blob([wbout], { type: "application/octet-stream" });
        FileSaver.saveAs(blob, "教师课表.xlsx");
    } catch (e) {
        console.error("导出Excel失败:", e);
        ElMessage.error("导出Excel失败，请查看控制台日志。");
    }
};

const digital2Chinese = (num, identifier) => {
    const character = [
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七", // 确保包含所有需要的数字
        // "八",
    ];
    if (identifier === "week") {
        return num === 0 || num === 7 ? "日" : character[num] || '';
    }
    return character[num] || '';
};

const clearListener = () => {
    teacherNo.value = "";
    initClassTableData(); // 清空教师选择时也清空课表
};

const handleSelectChange = (val) => {
    teacherNo.value = val;
    queryClass();
};

onMounted(() => {
    getSemester();
    getTeacherNo();
    // 初始加载时，如果 semesterId 和 teacherNo 都有值 (例如从 store 或默认值设置)，则查询
    // 这一步已在 getSemester 成功获取数据后处理
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}

.controls-container {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.control-item {
    margin-right: 15px;
}

.semester-select,
.class-select {
    width: 220px;
    /* 限制下拉框宽度 */
}

.course-info {
    white-space: pre-wrap;
    /* 保留空白和换行 */
    line-height: 1.5;
    /* 调整行高使内容更易读 */
    font-size: 13px;
    /* 可根据需要调整字体大小 */
}

.period {
    font-size: 12px;
    color: #666;
}
</style>